<?php
/**
 * CP管理
 * @author liangpan
 */
include_once dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'public.class.php';
class nl_cp extends nl_public
{
    static $base_table='nns_cp';
    static $sp_table='nns_mgtvbk_sp';
    static $arr_filed = array(
        'nns_id',
        'nns_name',
        'nns_contactor',
        'nns_telephone',
        'nns_email',
        'nns_addr',
        'nns_desc',
        'nns_type',
        'nns_state',
        'nns_create_time',
        'nns_modify_time',
        'nns_config',
        'nns_file_state_enable',
    );

    /**
     * 查询单个列表
     * @param object $dc 数据库对象
     * @param string $nns_id guid
     * @return Ambigous array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
     * @author liangpan
     * @date 2016-03-06
     */
    static public function query_by_id($dc,$nns_id)
    {
        $sql = "select * from " . self::$base_table . " where nns_id='{$nns_id}' limit 1";
        $result = nl_query_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库查询失败,sql:'.$sql);
        }
        $result = (isset($result[0]) && !empty($result[0])) ? $result[0] : null;
        return self::return_data(0,'OK',$result);
    }

    /**
     * 查询单个列表
     * @param object $dc 数据库对象
     * @param string $nns_id guid
     * @return Ambigous array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
     * @author liangpan
     * @date 2016-03-06
     */
    static public function query_by_id_by_db($db,$nns_id)
    {
        $sql = "select * from " . self::$base_table . " where nns_id='{$nns_id}' limit 1";
        $result = nl_query_by_db($sql, $db);
        if(!$result)
        {
            return self::return_data(1,'数据库查询失败,sql:'.$sql);
        }
        $result = (isset($result[0]) && !empty($result[0])) ? $result[0] : null;
        return self::return_data(0,'OK',$result);
    }

    /**
     * 添加CP
     * @param object $dc 数据库对象
     * @param array $params 数据数组
     * @return Ambigous <array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
     * @author liangpan
     * @date 2016-03-06
     */
    static public function add($dc,$params)
    {
        $str_time = date('Y-m-d H:i:s');
        if(!isset($params['nns_create_time']) || strlen($params['nns_create_time'])<1)
        {
            $params['nns_create_time'] = $str_time;
        }
        if(!isset($params['nns_modify_time']) || strlen($params['nns_modify_time'])<1)
        {
            $params['nns_modify_time'] = $str_time;
        }
        if(!isset($params['nns_id']) || strlen($params['nns_id'])<1)
        {
            return self::return_data(1,'CP_id为空');
        }
        $params = self::except_useless_params(self::$arr_filed, $params);
        if(empty($params))
        {
            return self::return_data(1,'参数为空');
        }
        $sql = self::make_insert_sql(self::$base_table, $params);
        $result = nl_execute_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库执行失败'.$sql);
        }

        global $g_bk_version_number;
        $bk_version_number = $g_bk_version_number == '1' ? true : false;
        unset($g_bk_version_number);
        global $g_project_name;
        $p_name = $g_project_name;
        unset($g_project_name);
        if ($bk_version_number)
        {
            //定义当前创建的cp的文件路径
            $file_path_v2_cp = dirname(dirname(dirname(__FILE__))).'/v2/ns_api/' . $p_name . '/message/' .$params['nns_id'];
            if(!is_dir($file_path_v2_cp)) mkdir($file_path_v2_cp,0777,true);

            //获取复制需要的cp的路径
            $cp_config =  json_decode($params['nns_config'],true);

            $use_other_cp = isset($cp_config['message_use_other_cp_parse']) && (int)$cp_config['message_use_other_cp_parse'] == 1 ? true : false;
            $other_cp_id = isset($cp_config['nns_other_cp_id'])? $cp_config['nns_other_cp_id'] : '';
            if ($use_other_cp && !empty($other_cp_id))
            {
                $other_cp_src = dirname(dirname(dirname(__FILE__))).'/v2/ns_api/' . $p_name . '/message/' . $other_cp_id;
                self::copy_file($other_cp_src, $file_path_v2_cp);
            }
            else
            {
                //import文件的生成
                $import_file = '<?php'.PHP_EOL;
                $import_file .= 'header(\'Content-Type: text/html; charset=utf-8\');'.PHP_EOL;
                //加载公共文件
                $import_file .='include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";'.PHP_EOL;
                $import_file .='\ns_core\m_load::load("ns_core.m_config");'.PHP_EOL;
                $import_file .='\ns_core\m_load::load("ns_model.message.message_queue");'.PHP_EOL;
                $import_file .='class import extends \ns_model\message\message_queue {'.PHP_EOL;
                $import_file .='public $arr_in_message = array('.PHP_EOL;
                $import_file .='\'base_info\'=>array('.PHP_EOL;
                $import_file .='\'nns_message_time\'=>\'\', //上游消息时间  年月日时分秒毫秒'.PHP_EOL;
                $import_file .='\'nns_message_id\'=>\'\',  //上游消息ID'.PHP_EOL;
                $import_file .='\'nns_cp_id\'=>\'\', //上游CP标示'.PHP_EOL;
                $import_file .='\'nns_message_xml\'=>\'\',  //上游原始的信息  可以为字符串 | xml | json 或则存放消息地址'.PHP_EOL;
                $import_file .='\'nns_message_content\'=>\'\',  //上游解析后的信息  可以为字符串 | xml | json  生成队列的基本信息'.PHP_EOL;
                $import_file .='\'nns_action\'=>\'\', //操作 行为'.PHP_EOL;
                $import_file .='\'nns_type\'=>\'\', //消息 类型'.PHP_EOL;
                $import_file .='\'nns_name\'=>\'\',  //消息名称'.PHP_EOL;
                $import_file .='\'nns_package_id\'=>\'\',  //包ID'.PHP_EOL;
                $import_file .='\'nns_xmlurlqc\'=>\'\', //广州电信悦ME MD5摘要'.PHP_EOL;
                $import_file .='\'nns_encrypt\'=>\'\', //广州电信悦ME 加密串'.PHP_EOL;
                $import_file .='\'nns_content_number\'=>\'\', //xml文件中包含的内容数量'.PHP_EOL;
                $import_file .='), //基本信息（存储于nns_mgtvbk_message表中）'.PHP_EOL;
                $import_file .=');'.PHP_EOL;
                $import_file .='public function __construct(){'.PHP_EOL;
                $import_file .='}'.PHP_EOL;
                $import_file .='public function import(){'.PHP_EOL;
                $import_file .='$result = $this->push($this->arr_in_message);'.PHP_EOL;
                $import_file .='}'.PHP_EOL;
                $import_file .='}'.PHP_EOL;
                $import_file .='$import = new import();'.PHP_EOL;
                $import_file .='$result_import = $import->import();'.PHP_EOL;
                $import_file .='return $result_import;'.PHP_EOL;
                $import_file_name = 'import.php';
                //生成import文件
                $import_file_path = $file_path_v2_cp . DIRECTORY_SEPARATOR . $import_file_name;
                if (!file_exists($import_file_path))
                {
                    file_put_contents($import_file_path,$import_file);
                }

                //message消息解析文件
                $message_file = '<?php'.PHP_EOL;
                //加载公共文件
                $message_file .='include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";'.PHP_EOL;
                $message_file .='\ns_core\m_load::load("ns_model.message.message_explain");'.PHP_EOL;
                $message_file .='\ns_core\m_load::load("ns_core.m_config");'.PHP_EOL;
                $message_file .='class message extends \ns_model\message\message_explain {'.PHP_EOL;
                $message_file .='public function explain($message){'.PHP_EOL;
                $message_file .='}'.PHP_EOL;
                $message_file .='/**'.PHP_EOL;
                $message_file .='  * @param $arr_data //封装好了的反馈信息 array('.PHP_EOL;
                $message_file .='*                                          \'cdn_id\' => ,注入cdn的id'.PHP_EOL;
                $message_file .='*                                          \'site_id\' => ,配置的站点id'.PHP_EOL;
                $message_file .='*                                          \'mg_asset_type\' => ,注入媒资类型'.PHP_EOL;
                $message_file .='*                                          \'mg_asset_id\' => ,主媒资的消息注入id'.PHP_EOL;
                $message_file .='*                                          \'mg_part_id\' => ,分集的消息注入id'.PHP_EOL;
                $message_file .='*                                          \'mg_file_id\' => ,);片源的消息注入id,'.PHP_EOL;
                $message_file .='*/'.PHP_EOL;
                $message_file .='public function is_ok($message_id, $code, $reason, $arr_data, $sp_id){'.PHP_EOL;
                $message_file .='}'.PHP_EOL;
                $message_file .='}'.PHP_EOL;
                $message_file_name = 'message.class.php';
                //生成message文件
                $message_file_path = $file_path_v2_cp . DIRECTORY_SEPARATOR . $message_file_name;
                if (!file_exists($message_file_path))
                {
                    file_put_contents($message_file_path,$message_file);
                }
            }
        }

        return self::return_data(0,'ok');
    }

    /**
     * 复制文件到新的路径
     * @param $other_cp_src
     * @param $newdir
     */
    static public function copy_file($other_cp_src, $newdir)
    {
        $dir = opendir($other_cp_src);
        if ($dir)
        {
            while (($file = readdir($dir)) !== false)
            {
                $fileFrom = $other_cp_src . DIRECTORY_SEPARATOR . $file;
                $fileTo = $newdir . DIRECTORY_SEPARATOR . $file;
                if ($file == '.' || $file == '..') continue;
                if (is_dir($fileFrom))
                {
                    mkdir($fileTo,0777);
                    self::copy_file($fileFrom, $fileTo);
                }
                else
                {
                    @copy($fileFrom, $fileTo);
                }
            }
        }
    }
    /**
     * 修改CP
     * @param object $dc 数据库对象
     * @param array $params 数据数组
     * @return Ambigous <array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
     * @author liangpan
     * @date 2016-03-06
     */
    static public function edit($dc,$params,$nns_id)
    {
        $nns_id = is_array($nns_id) ? $nns_id : array($nns_id);
        if(empty($nns_id))
        {
            return self::return_data(1,'全局错误日志_id为空');
        }
        $params = self::except_useless_params(self::$arr_filed, $params);
        if(empty($params))
        {
            return self::return_data(1,'参数为空');
        }
        $params['nns_modify_time'] = date("Y-m-d H:i:s");
        $sql = self::make_update_sql(self::$base_table, $params,array('nns_id'=>$nns_id));
        $result = nl_execute_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库执行失败'.$sql);
        }

        return self::return_data(0,'ok');
    }


    /**
     * 查询CP列表
     * @param object $dc 数据库对象
     * @param array $params 查询参数
     * @param array $page_info 分页信息
     * @return Ambigous array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
     * @author liangpan
     * @date 2016-03-06
     */
    static public function query($dc,$page_info=null)
    {
        self::$str_where = (strlen(self::$str_where) > 5) ? trim(self::$str_where,'and ') : '';
        $str_limit = self::make_page_limit($page_info);
        $sql="select * from " . self::$base_table . self::$str_where . " {$str_limit} ";
        $sql_count = "select count(*) as count from " . self::$base_table . " " . self::$str_where;
        // 		echo $sql;die;
        $result_count = nl_query_by_db($sql_count,  $dc->db());
        $result = nl_query_by_db($sql, $dc->db());
        self::init_where();
        if(!$result || !$result_count)
        {
            return self::return_data(1,"查询数据失败");
        }
        return self::return_data(0,"查询数据成功",$result,$result_count);
    }

    /**
     * 查询单个列表
     * @param object $dc 数据库对象
     * @return Ambigous array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
     * @author liangpan
     * @date 2016-03-06
     */
    static public function query_exsist($dc,$type='')
    {
        $sql = "select count(*) as count from nns_cp ";
        if(strlen($type) >0)
        {
            $sql.=" where nns_type='{$type}' ";
        }
        $result = nl_query_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库查询失败,sql:'.$sql);
        }
        $result = isset($result[0]['count']) ? $result[0]['count'] : 0;
        return self::return_data(0,'OK',$result);
    }

    /**
     * 查询所有
     * @param object $dc 数据库对象
     * @return array array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
     * @author liangpan
     * @date 2016-03-06
     */
    static public function query_all($dc,$type='',$state='')
    {
        $sql="select * from " . self::$base_table;
        if(strlen($type) >0)
        {
            $sql.=" where nns_type='{$type}' ";
        }
        if(strlen($state) >0)
        {
            $sql.=" where nns_state='{$state}' ";
        }
        $result = nl_query_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库查询失败,sql:'.$sql);
        }
        return self::return_data(0,'OK',$result);
    }

    /**
     * 查询所有
     * @param object $dc 数据库对象
     * @return Ambigous array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
     * @author liangpan
     * @date 2016-03-06
     */
    static public function query_file_pack_state($dc,$state)
    {
        $sql="select * from " . self::$base_table . " where nns_file_state_enable='{$state}'";
        $result = nl_query_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库查询失败,sql:'.$sql);
        }
        return self::return_data(0,'OK',$result);
    }
    /**
     * 删除
     * @param object $dc 数据库对象
     * @return Ambigous array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
     * @author liangpan
     * @date 2016-03-06
     */
    static public function delete($dc,$nns_id)
    {
        if(strlen($nns_id) <1)
        {
            return self::return_data(1,'CP_id为空');
        }
        $sql = "delete from " . self::$base_table . " where nns_id='{$nns_id}' ";
        $result = nl_execute_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库查询失败,sql:'.$sql);
        }
        return self::return_data(0,'OK');
    }
    /**
     * 查询多个CP列表
     * @param object $dc 数据库对象
     * @param array $cp_id_arr array(id1,id2)
     * @return Ambigous array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
     * @author liangpan
     * @date 2016-03-06
     */
    static public function query_by_more_id($dc,$cp_id_arr)
    {
        if(!is_array($cp_id_arr) || empty($cp_id_arr))
        {
            return self::return_data(1,'传参不是数组或为空');
        }
        $ids_arr = implode("','", $cp_id_arr);
        $ids_arr = "'".$ids_arr."'";
        $sql = "select * from " . self::$base_table . " where nns_id in (" . $ids_arr . ")";
        $result = nl_query_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库查询失败,sql:'.$sql);
        }
        return self::return_data(0,'OK',$result);
    }


    /**
     * 查询多个CP列表
     * @param object $dc 数据库对象
     * @param array $cp_id_arr array(id1,id2)
     * @return Ambigous array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
     * @author liangpan
     * @date 2016-03-06
     */
    static public function query_by_more_id_by_db($db,$cp_id_arr)
    {
        if(!is_array($cp_id_arr) || empty($cp_id_arr))
        {
            return self::return_data(1,'传参不是数组或为空');
        }
        $ids_arr = implode("','", $cp_id_arr);
        $ids_arr = "'".$ids_arr."'";
        $sql = "select * from " . self::$base_table . " where nns_id in (" . $ids_arr . ")";
        $result = nl_query_by_db($sql, $db);
        if(!$result)
        {
            return self::return_data(1,'数据库查询失败,sql:'.$sql);
        }
        return self::return_data(0,'OK',$result);
    }

    /**
     * 查询单条CP的基本信息
     * @param object $dc 数据库对象
     * @param string $cp_id cp_id
     * @return Ambigous <array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
     * @author liangpan
     * @date 2016-09-10
     */
    static public function get_cp_config($dc, $cp_id=null)
    {
        if(strlen($cp_id) < 1)
        {
            return self::return_data(1,"cp id 错误，传入参数为：".var_dump($cp_id,true));
        }
        $result_info=self::query_by_id($dc, $cp_id);
        if($result_info['ret'] !=0)
        {
            return self::return_data(1,"cp id 查询 sql 错误：".var_dump($result_info['reason'],true));
        }
        $last_config = null;
        if(isset($result_info['data_info']['nns_config']) && strlen($result_info['data_info']['nns_config']) >0)
        {
            $result_info_config = json_decode($result_info['data_info']['nns_config'],true);
            $last_config['nns_config']=(is_array($result_info_config) && !empty($result_info_config)) ?  $result_info_config : null;
            unset($result_info['data_info']['nns_config']);
        }
        if(is_array($result_info['data_info']) && !empty($result_info['data_info']))
        {
            foreach ($result_info['data_info'] as $key=>$val)
            {
                $last_config['base_info'][$key] = $val;
            }
        }
        return self::return_data(0,"ok",$last_config);
    }

    /**
     * 查询是否存在
     * @param unknown $dc
     * @param string $str_param
     */
    static public function query_unique($dc,$str_param=null)
    {
        $sql="select count(*) as count from " . self::$base_table;
        if(isset($str_param) && strlen($str_param))
        {
            $str_param = trim($str_param);
        }
        $is_set_where = substr($str_param, 0,5);
        if(strtolower($is_set_where) != 'where')
        {
            $str_param = " where ".$str_param;
        }
        $str_param = (strtolower($is_set_where) != 'where') ? " where ".$str_param : " ".$str_param;
        $sql = $sql.$str_param;
        $result = nl_query_by_db($sql, $dc->db());
        if(!$result)
        {
            return self::return_data(1,"查询数据失败".$sql);
        }
        return self::return_data(0,"查询数据成功".$sql,$result);
    }
}
